<?php
class AppController extends Controller {
	public $components = array('AutoLogin', 'Auth', 'Session');
	/**
	 * @var AuthComponent
	 */
	public $Auth;
	/**
	 * @var SessionComponent
	 */
	public $Session;
	
	public function beforeFilter(){
		$this->Auth->deny('*');
		$this->Auth->authError 			= __('Please login to view this page.', true);
		if (Configure::read('User.useUsername')) {
			$this->Auth->loginError 	= __('Incorect username or password.', true);
		} else {
			$this->Auth->loginError 	= __('Incorect email or password.', true);
			$this->Auth->fields 		= array('username' => 'email', 'password' => 'password');
		}
		$sess = $this->Session->read('Auth');
		if (isset($sess['redirect']) AND $sess['redirect'] != '') {
			$this->Auth->loginRedirect 	= $sess['redirect'];
		} else {
			$this->Auth->loginRedirect 	= array('controller' => 'index', 'action' => 'index');
		}
		$this->Auth->logoutRedirect = array('controller' => 'index', 'action' => 'index');
		$this->Auth->userScope 		= array('User.active' => 1);
		$language = $this->Session->read('App.Language');
		if ($language != '') {
			Configure::write('Config.language', $language);
		}
		$this->set('isAuthorized', $this->Auth->isAuthorized());
	}

	public function redirect($url='', $status = null, $exit = true) {
		if (ENV != 'test') {
			if ($url == '') {
				$url = '/';
			}
			parent::redirect($url, $status, $exit);
		}
	}
	
    public function _autoLogin($user) {
    	$this->set('isAuthorized', $this->Auth->isAuthorized());
    }
    
	public function updateUserSession($id) {
		$user = $this->User->read(null, $id);
		$this->updateSession($user['User']);
	}

	public function updateSession($info) {
		$this->Session->write($this->Auth->sessionKey, $info);
	}

	public function respondOk($code='', $data='') {
		return array('status'=>'OK', 'code'=>$code, 'data'=>$data);
	}
	
	public function respondFailed($code='', $data='') {
		return array('status'=>'FAIL', 'code'=>$code, 'data'=>$data);
	}
}
